import { Canvas, Group, Path, Rect } from '@shopify/react-native-skia';
import React, { useCallback, useState } from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
import { GridCell, GridLayout } from './LayoutEditor';

// 拼图项接口
interface CollageItem {
  id: string;
  x: number;
  y: number;
  width: number;
  height: number;
  imageSource?: string;
}

// 拼图组件属性
interface GridCollageProps {
  gridLayout: GridLayout;
  canvasWidth: number;
  canvasHeight: number;
  spacing?: number;
  backgroundColor?: string;
  onItemSelect?: (item: GridCell) => void;
  onImageAdd?: (itemId: string, imageSource: string) => void;
  onTap?: (x: number, y: number) => void;
}

const GridCollage: React.FC<GridCollageProps> = ({
  gridLayout,
  canvasWidth,
  canvasHeight,
  spacing = 10,
  backgroundColor = '#FFFFFF',
  onItemSelect,
  onImageAdd,
  onTap,
}) => {
  const [selectedItem, setSelectedItem] = useState<string | null>(null);

  // 简单的宫格渲染方法
  const renderGrid = () => {
    console.log("renderGrid called with layout:", gridLayout);
    
    if (!gridLayout || gridLayout.key === 'none') {
      return null;
    }

    const { rows, cols } = gridLayout;
    console.log("Grid dimensions:", { rows, cols, canvasWidth, canvasHeight });

    // 计算宫格尺寸，自适应画布
    const availableWidth = canvasWidth - (spacing * (cols + 1));
    const availableHeight = canvasHeight - (spacing * (rows + 1));
    const cellWidth = availableWidth / cols;
    const cellHeight = availableHeight / rows;

    console.log("Calculated cell size:", { cellWidth, cellHeight });

    const items: CollageItem[] = [];

    // 生成宫格项目
    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const x = spacing + col * (cellWidth + spacing);
        const y = spacing + row * (cellHeight + spacing);
        
        items.push({
          id: `${row}-${col}`,
          x,
          y,
          width: cellWidth,
          height: cellHeight,
        });
      }
    }

    console.log("Generated items:", items);

    return (
      <Group>
        {/* 渲染每个宫格 */}
        {items.map((item) => (
          <Group key={item.id}>
            {/* 宫格边框 */}
            <Path
              path={`M ${item.x} ${item.y} L ${item.x + item.width} ${item.y} L ${item.x + item.width} ${item.y + item.height} L ${item.x} ${item.y + item.height} Z`}
              strokeWidth={2}
              color={selectedItem === item.id ? "#007AFF" : "#333333"}
              style="stroke"
            />
            {/* 宫格背景 */}
            <Rect
              x={item.x}
              y={item.y}
              width={item.width}
              height={item.height}
              color={selectedItem === item.id ? "rgba(0, 122, 255, 0.1)" : "rgba(240, 240, 240, 0.3)"}
            />
          </Group>
        ))}
      </Group>
    );
  };

  // 处理宫格点击
  const handleGridTap = useCallback((x: number, y: number) => {
    console.log("Grid tapped at:", x, y);
    
    // 简单的点击检测 - 基于宫格布局
    const { rows, cols } = gridLayout;
    const availableWidth = canvasWidth - (spacing * (cols + 1));
    const availableHeight = canvasHeight - (spacing * (rows + 1));
    const cellWidth = availableWidth / cols;
    const cellHeight = availableHeight / rows;

    // 找到点击的宫格
    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const itemX = spacing + col * (cellWidth + spacing);
        const itemY = spacing + row * (cellHeight + spacing);
        
        if (x >= itemX && x <= itemX + cellWidth && y >= itemY && y <= itemY + cellHeight) {
          console.log("Clicked grid cell:", { row, col });
          
          const gridCell: GridCell = {
            id: `${row}-${col}`,
            row,
            col,
            x: itemX,
            y: itemY,
            width: cellWidth,
            height: cellHeight,
            path: `M ${itemX} ${itemY} L ${itemX + cellWidth} ${itemY} L ${itemX + cellWidth} ${itemY + cellHeight} L ${itemX} ${itemY + cellHeight} Z`
          };
          
          setSelectedItem(gridCell.id);
          onItemSelect?.(gridCell);
          onImageAdd?.(gridCell.id, '');
          return;
        }
      }
    }
    
    onTap?.(x, y);
  }, [gridLayout, canvasWidth, canvasHeight, spacing, onItemSelect, onImageAdd, onTap]);

  if (!gridLayout || gridLayout.key === 'none') {
    return null;
  }

  return (
    <TouchableOpacity 
      style={StyleSheet.absoluteFill}
      onPress={(event) => {
        const { locationX, locationY } = event.nativeEvent;
        handleGridTap(locationX, locationY);
      }}
      activeOpacity={1}
    >
      <Canvas style={StyleSheet.absoluteFill}>
        {renderGrid()}
      </Canvas>
    </TouchableOpacity>
  );
};

export default GridCollage;
